# 
# Download Control code is copyright Kumar McMillan and contributors.
# It is dual licensed under:
#   Gnu Public License Version 3
#   Limited Commercial License
#
# See the following wiki page for details:
# http://code.google.com/p/downloadcontrol/wiki/AboutTheLicense
#

from django.conf import settings
from django.core.urlresolvers import reverse
from django.template import loader, Context, RequestContext
from django.http import HttpResponse, HttpResponseRedirect
from downloadcontrol.models import AWSConfig, DownloadAccess
from jsonutils import as_json
from downloadcontrol import s3_utils

def example(request):
    try:
        config = AWSConfig.instance()
    except EnvironmentError:
        return HttpResponseRedirect(reverse('downloadcontrol.activate-datastore-admin'))
    ctx = RequestContext(request, {
        'request_download_url': reverse('downloadcontrol.request-download')
    })
    tpl = loader.get_template('downloadcontrol/example.html')
    return HttpResponse(tpl.render(ctx))

@as_json
def _request_download(request):
    result = {
        'success': False,
        'msg': None,
        'url': None
    }
    if not request.POST:
        result['msg'] = 'Internal error'
        return result
    if not request.POST.get('access_code'):
        result['msg'] = 'Internal error'
        return result
        
    code = request.POST['access_code']
    rs = DownloadAccess.all().filter("access_code =", code)
    if not rs.count(1):
        result['msg'] = 'Access denied'
        return result
    else:
        access = rs[0]
    if not access.is_valid:
        result['msg'] = "Invalid code"
        return result
    
    try:
        config = AWSConfig.instance()
    except EnvironmentError:
        return HttpResponseRedirect(reverse('downloadcontrol.activate-datastore-admin'))
    result['expires_in'] = 60*5 # five min
    result['url'] =  s3_utils.get_authenticated_url(access.s3_key, result['expires_in'],
                                aws_access_key_id=config.access_key_id, 
                                aws_secret_access_key=config.secret_access_key)
    access.num_requests += 1
    access.save()
    result['success'] = True
    
    return result

def _activate_datastore_admin(request):
    # entities don't exist until they have data:
    inited = False
    if AWSConfig.all().count(1) == 0:
        c = AWSConfig(
            access_key_id='replace with your S3 Access Key ID', 
            secret_access_key='replace with your S3 Secret Access Key')
        c.save()
        inited = True
    if DownloadAccess.all().count(1) == 0:
        c = DownloadAccess(access_code='BBBBB', s3_key='somepath/somefile.zip')
        c.save()
        inited = True
    if not inited:
        return HttpResponse("""
        No initialization necessary. Go back to the <a href="%(example_url)s">example</a>
        """ % {
            'example_url': reverse('downloadcontrol.example')
        })
    else:
        return HttpResponse("""
        Hi! Almost done. Now add some values to AWSConfig and DownloadAccess in 
        <a href="/_ah/admin/datastore">The SDK Datastore admin</a>
        The go back to the <a href="%(example_url)s">example</a>
        """ % {
            'example_url': reverse('downloadcontrol.example')
        })
